<script setup>
import { ref, onMounted } from 'vue'
let selectedShip = ref([])
/**
 * 
 * @param {点坐标} point 
 * @param {矩形四个角坐标} polygon 
 * @returns {inside} 判断某个点是否在矩形框内,返回值为布尔值
 */
function isPointInRectangle (point, rectangleCorners) {
  const [topLeft, topRight, bottomLeft, bottomRight] = rectangleCorners
  const maxX = Math.max(topLeft.lng, topRight.lng, bottomLeft.lng, bottomRight.lng)
  const minX = Math.min(topLeft.lng, topRight.lng, bottomLeft.lng, bottomRight.lng)
  const maxY = Math.max(topLeft.lat, topRight.lat, bottomLeft.lat, bottomRight.lat)
  const minY = Math.min(topLeft.lat, topRight.lat, bottomLeft.lat, bottomRight.lat)
  return point.lng <= maxX && point.lng >= minX && point.lat <= maxY && point.lat >= minY
}

let map
let drawingManager
let rectangleOverlay
let markers = ref([]) // 用于存储标记点
let Coordinatepoints = ref([]) // 代表存储的矩形的四个角坐标
// 创建标记点函数
function createMarker(lng, lat) {
  var point = new BMapGL.Point(lng, lat)
  var myIcon = new BMapGL.Icon("/src/assets/111.webp", new BMapGL.Size(10, 10))
  var marker = new BMapGL.Marker(point, { icon: myIcon })
  markers.value.push(marker)
}

// 循环添加标记点到地图函数
function addMarkersToMap() {
  markers.value.forEach(marker => {
    map.addOverlay(marker)
  })
}
onMounted(() => {
  const center = new BMapGL.Point(116.307852, 40.057031)
  map = new BMapGL.Map("map")
  map.centerAndZoom(center, 15) //设置中心点
  var navi3DCtrl = new BMapGL.NavigationControl3D({ //添加3D旋转控件
    anchor: BMAP_ANCHOR_TOP_RIGHT   // 控件的位置在右上角
  })  // 添加3D控件
  map.addControl(navi3DCtrl) // 添加3D/2D旋转的工具图标

  createMarker(116.307852, 40.057031)  // 循环批量添加maker点
  createMarker(116.308, 40.058)
  createMarker(116.309, 40.059)
  // 批量添加标记点到地图
  addMarkersToMap()

  drawingManager = new BMapGLLib.DrawingManager(map, {   // 创建鼠标绘制工具库
    isOpen: false,
    enableDrawingTool: true,
    drawingToolOptions: {
      anchor: BMAP_ANCHOR_TOP_RIGHT,  // 位于右上角
      offset: new BMapGL.Size(5, 5),
      drawingModes: [BMAP_DRAWING_RECTANGLE],  // 只保留矩形(去掉默认全部展示)
    },
  })

  drawingManager.addEventListener('overlaycomplete', (e) => {  // 绘制图形完成时会触发的事件
    if (selectedShip.value.length > 0) {  // 当我每次绘制都会保存绘制的对象,每次绘制完成都会判断如果大于0就清空前面的,因为这里要求矩形只能画一个
      console.log('只能选择一个矩形')
      clearAll()  // 清除所有的覆盖物点
    }
    selectedShip.value.push(e.overlay)  // 将已经画好的存起来,通过长度用于判断是否存在多个覆盖物
    Coordinatepoints.value = []  // 这个是存储的每次绘制的矩形的四个点坐标,每次都是新矩形,因此每次会话都要先清空再添加
    if (e.drawingMode == BMAP_DRAWING_RECTANGLE) {  // 判断绘制的图形是否为矩形(是矩形就进if)
      // 保存矩形覆盖物
      rectangleOverlay = e.overlay  
      // 获取矩形的边界
      const bounds = rectangleOverlay.getBounds()
      const sw = bounds.getSouthWest()
      const ne = bounds.getNorthEast()

      // 计算四个角的坐标(下面四个变量获取的是矩形的四个角坐标)
      let topLeft = new BMapGL.Point(sw.lng, ne.lat)
      let topRight = ne
      let bottomLeft = sw
      let bottomRight = new BMapGL.Point(ne.lng, sw.lat)
      Coordinatepoints.value.push(topLeft, topRight, bottomLeft, bottomRight)  // 添加矩形四个角信息
      console.log('isPointInRectangle',isPointInRectangle({ lng: 116.307852, lat: 40.057031 }, Coordinatepoints.value));  // 判断当前点是否在矩形内,true/false
    }
  })

  // 传入地图对象和经纬度可以实时画轨迹线(这里模拟的是鼠标的移动事件,鼠标每次移动就调用一次将每次移动的坐标点用于绘制轨迹)
  function drawLineOnMap (map, lng, lat) {
    var point = new BMapGL.Point(lng, lat)

    if (!map.customData || !Array.isArray(map.customData.points)) {
      map.customData = { points: [point] }
    } else {
      map.customData.points.push(point)
    }
    if (map.customData.points.length > 1) {
      var polyline = new BMapGL.Polyline(map.customData.points, {
        strokeColor: "blue", // 线段颜色
        strokeWeight: 4,     // 线段宽度
        strokeOpacity: 0.7  // 线段透明度
      })
      // // 清除旧的折线
      // if (map.customData.polyline) {
      //     map.removeOverlay(map.customData.polyline);
      // }
      // 添加折线
      map.addOverlay(polyline)
      map.customData.polyline = polyline
    }
  }

  // 这段代码是鼠标经过会绘制折线
  map.addEventListener("mousemove", function (e) {
    var pixel = new BMapGL.Pixel(e.pixel.x, e.pixel.y)
    var lngLat = map.pixelToPoint(pixel)
    var lng = lngLat.lng
    var lat = lngLat.lat
    // console.log("经度：" + lng + "，纬度：" + lat)  //鼠标经过的经纬度坐标
    drawLineOnMap(map, lng, lat) //鼠标移动就绘制轨图
  })

  // 开启绘制
  drawingManager.open()
})

// 清空所有覆盖物
function clearAll () {
  // 循环遍历清除
  for (var i = 0; i < selectedShip.value.length; i++) {
    map.removeOverlay(selectedShip.value[i])
  }
  selectedShip.value.length = 0
}
</script>

<template>
  <div>
    <div id="map"></div>
    <button @click="clearAll">清除矩形</button>
  </div>
</template>

<style>
#map {
  height: 500px;
  width: 1000px;
  margin: 0;
}
/* 将工具栏容器浮动到右上角 */
.BMapGLLib_Drawing {
  width: 100%;
}
.BMapGLLib_Drawing_panel {
  float: right;
  margin-right: 60px;
  margin-top: 20px;
}
/* 更改指南针的位置(默认的位置不是理想的) */
.BMap_noprint.anchorTR {
  margin-right: 50px;
  margin-top: 20px;
}
</style>
